﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CarbonKit.Core.Silverlight3 {
  using System.Collections;
  using System.Reflection;
  using System.Threading;

  using Extensions;

  public static class EnumHelper {

    public static IList ToList(Type type) {
      Array enumValues = GetValues(type);
      IList list = new List<object>();
      foreach (var value in enumValues) {
        list.Add(new KeyValuePair<object, string>(Convert.ChangeType(value, Enum.GetUnderlyingType(type), Thread.CurrentThread.CurrentUICulture), (value as Enum).GetDescription()));
      }

      return list;
    }

    public static IList ToList<T>(T defaultValue) where T : struct, IConvertible {
      if (!typeof(T).IsEnum) throw new ArgumentException("T must be an enumeration");

      IList list = new List<T>();
      Type type = typeof(T);
      Array enumValues = GetValues(type);

      foreach (T value in enumValues) {
        list.Add(new KeyValuePair<object, string>(Convert.ChangeType(value, Enum.GetUnderlyingType(type), Thread.CurrentThread.CurrentUICulture), (value as Enum).GetDescription()));
      }

      return list;
    }

    public static T[] GetValues<T>() {
      Type enumType = typeof(T);

      if (!enumType.IsEnum) {
        throw new ArgumentException("Type '" + enumType.Name + "' is not an enum");
      }

      List<T> values = new List<T>();

      var fields = from field in enumType.GetFields()
                   where field.IsLiteral
                   select field;

      foreach (FieldInfo field in fields) {
        object value = field.GetValue(enumType);
        values.Add((T)value);
      }

      return values.ToArray();
    }

    public static object[] GetValues(Type enumType) {
      if (!enumType.IsEnum) {
        throw new ArgumentException("Type '" + enumType.Name + "' is not an enum");
      }

      List<object> values = new List<object>();

      var fields = from field in enumType.GetFields()
                   where field.IsLiteral
                   select field;

      foreach (FieldInfo field in fields) {
        object value = field.GetValue(enumType);
        values.Add(value);
      }

      return values.ToArray();
    }
  }
}
